package com.hundsun.cprs.yyt.common.push.jpush;

import java.text.MessageFormat;
import java.util.Map;

import com.hundsun.cprs.yyt.common.push.AbstractPushService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.hundsun.cprs.yyt.common.push.AbstractPushService;
import com.hundsun.cprs.yyt.common.push.PushConfig;

import cn.jiguang.common.ClientConfig;
import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jpush.api.JPushClient;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Options;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.notification.AndroidNotification;
import cn.jpush.api.push.model.notification.IosNotification;
import cn.jpush.api.push.model.notification.Notification;

@Service
public class JPushServiceImpl extends AbstractPushService {
    
    protected static final Logger LOG = LoggerFactory.getLogger(JPushServiceImpl.class);

    @Autowired
    private PushConfig pushConfig;
    
    @Override
    public void sendPush(String title, String content,Map<String, String> extras, String... alias) {
        if (!pushConfig.isOn()) {
            LOG.warn("APP推送业务未开启,忽略...");
            return;
        }
        
        if (alias == null) {
            return;
        }
        
        if (extras != null && extras.containsKey("msgType")) {
            extras.put("url", MessageFormat.format(pushConfig.getLinkUrl(), extras.get("path"),extras.get("msgType")));
        }
        
        ClientConfig clientConfig = ClientConfig.getInstance();
        JPushClient jpushClient = new JPushClient(pushConfig.getJpushMasterSecret(),pushConfig.getJpushAppKey(), null, clientConfig);
        
        PushPayload payload = PushPayload.newBuilder()
                                .setPlatform(Platform.all())
                                .setAudience(Audience.alias(alias))
                                .setNotification(Notification.newBuilder()
                                            .setAlert(content)
                                            .addPlatformNotification(AndroidNotification.newBuilder()
                                                        .setTitle(title)
                                                        .addExtras(extras).build())
                                            .addPlatformNotification(IosNotification.newBuilder()
                                                        .incrBadge(1)
                                                        .addExtras(extras).build())
                                            .build())
                                .setOptions(Options.newBuilder().setApnsProduction(true).build())
                                .build();
        try {
            LOG.info("send PushPayload - " + payload);
            PushResult result = jpushClient.sendPush(payload);
            int status = result.getResponseCode();
            LOG.info("Got result - " + result);
        } catch (APIConnectionException e) {
            LOG.error("Connection error. Should retry later. ", e);
            LOG.error("Sendno: " + payload.getSendno());

        } catch (APIRequestException e) {
            LOG.error("Error response from JPush server. Should review and fix it. ", e);
            LOG.info("HTTP Status: " + e.getStatus());
            LOG.info("Error Code: " + e.getErrorCode());
            LOG.info("Error Message: " + e.getErrorMessage());
            LOG.info("Msg ID: " + e.getMsgId());
            LOG.error("Sendno: " + payload.getSendno());
        }
        
    }

    @Override
    public void broadcast(String title, String content) {
        if (!pushConfig.isOn()) {
            LOG.warn("APP推送业务未开启,忽略...");
            return;
        }
        
        ClientConfig clientConfig = ClientConfig.getInstance();
        JPushClient jpushClient = new JPushClient(pushConfig.getJpushMasterSecret(),pushConfig.getJpushAppKey(), null, clientConfig);
        PushPayload payload = PushPayload.newBuilder()
                                .setPlatform(Platform.all())
                                .setAudience(Audience.all())
                                .setNotification(Notification.alert(content))
                                .setOptions(Options.newBuilder().setApnsProduction(true).build())
                                .build();
        try {
            PushResult result = jpushClient.sendPush(payload);
            int status = result.getResponseCode();
            LOG.info("Got result - " + result);
        } catch (APIConnectionException e) {
            LOG.error("Connection error. Should retry later. ", e);
            LOG.error("Sendno: " + payload.getSendno());

        } catch (APIRequestException e) {
            LOG.error("Error response from JPush server. Should review and fix it. ", e);
            LOG.info("HTTP Status: " + e.getStatus());
            LOG.info("Error Code: " + e.getErrorCode());
            LOG.info("Error Message: " + e.getErrorMessage());
            LOG.info("Msg ID: " + e.getMsgId());
            LOG.error("Sendno: " + payload.getSendno());
        }
    }

}
